package com.yl.ylnews.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 网络缓存工具类:主要使用Asynctask(异步封装的工具,对线程池+handler进行封装,可用实现异步请求和主界面更新)
 */

public class NetCacheUtils {

    private static final String TAG = "NetCacheUtils";
    private HttpURLConnection conn;
    private LocalCacheUtils mLocalCacheUtils;

    public void getBitmapFromNet(ImageView imageView, String url){
        new BitmapTask().execute(imageView, url);

    }

    /**
     * 三个范型的意义:1,doInBackground里面的参数类型 2,onProgressUpdate的参数类型 3,是doPostExecute 的参数类型,以及doInBacaGround的返回值类型
     */
    private class BitmapTask extends AsyncTask<Object,Integer,Bitmap>{

        private ImageView imageView;
        private String url;

        //1.预加载,运行在主线程
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        //2.核心方法,运行在子线程,表示正在加载,可用直接异步请求
        @Override
        protected Bitmap doInBackground(Object...params) {
            imageView = (ImageView) params[0];
            url = (String) params[1];
            imageView.setTag(1, url);
            Bitmap bitmap = download(url);
            return bitmap;

        }

        //3.更新进度的方法,运行在主线程
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        //4,核心方法,运行在主线程,加载结束调用,可用直接更新UI
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                String url = (String) imageView.getTag();
                imageView.setImageBitmap(bitmap);
                Log.d(TAG, "onPostExecute: 从网络下载图片");

                mLocalCacheUtils.setLocalCache(url, bitmap);//缓存到本地
            }
            super.onPostExecute(bitmap);
        }
    }

    public Bitmap download(String url){
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.connect();
            int responseCode = conn.getResponseCode();
            if (responseCode==200) {//连接成功
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        return null;
    }
}
